package org.zhangkun.jmsg.util;

import java.io.File;
import java.util.ArrayList;

public class FileScanner extends Thread {

	private long allSize = 0;
	private ScannerFilesListener listener;

	private ArrayList<String> path = new ArrayList<String>();

	private boolean stop = false;

	public FileScanner() {
		setName("FileScanner Thread");
	}

	public void append(String path) {
		this.path.add(path);
	}

	public long getAllSize() {
		return allSize;
	}

	public ScannerFilesListener getListener() {
		return listener;
	}

	public ArrayList<String> getPath() {
		return path;
	}

	public boolean isStop() {
		return stop;
	}

	public void run() {
		for (int index = 0; index < path.size(); index++) {
			String path = this.path.get(index);
			allSize = 0;
			if (FileUtil.isFile(path)) {
				allSize = FileUtil.getFileSize(path);
			} else {
				ArrayList<String> folders = new ArrayList<String>();
				folders.add(path);
				for (int i = 0; i < folders.size(); i++) {
					File f = new File(folders.get(i));
					File[] ff = f.listFiles();
					if (ff != null)
						for (int j = 0; j < ff.length; j++) {
							String fp = ff[j].getAbsolutePath();
							if (listener != null)
								listener.progress(fp, i, folders.size());
							if (stop == true) {
								if (listener != null) {
									for (int t = index; t < this.path.size(); t++)
										listener.finishScan(
												this.path.get(t),
												0,
												(t == this.path.size() - 1 ? true
														: false));
								}
								return;
							}

							if (ff[j].isFile()) {
								allSize += ff[j].length();
							} else {
								folders.add(fp);
							}
						}
				}
			}
			if (listener != null)
				listener.finishScan(path, allSize,
						(index == this.path.size() - 1 ? true : false));
		}
	}

	public void setAllSize(long allSize) {
		this.allSize = allSize;
	}

	public void setListener(ScannerFilesListener listener) {
		this.listener = listener;
	}

	public void setStop(boolean stop) {
		this.stop = stop;
	}

}
